using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using LayoutViewer.Views;
using System;

namespace LayoutViewer.Panels
{
    public partial class TitleBar : UserControl
    {

        public static readonly StyledProperty<string> TitleProperty = AvaloniaProperty.Register<TitleBar, string>(nameof(Title));
        public string Title
        {
            get => GetValue(TitleProperty);
            set => SetValue(TitleProperty, value);
        }

        public static readonly StyledProperty<bool> CanFullScreenProperty = AvaloniaProperty.Register<TitleBar, bool>(nameof(CanFullScreen));
        public bool CanFullScreen
        {
            get => GetValue(CanFullScreenProperty);
            set => SetValue(CanFullScreenProperty, value);
        }

        public TitleBar()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }

        private void Minsize_Tapped(object sender, RoutedEventArgs e)
        {
            MainWindow.Instance.WindowState = WindowState.Minimized;
        }

        private Window GetWindow(IControl control)
        {
            var parent = control.Parent;
            return parent != null ? parent is Window window ? window : GetWindow(parent) : throw new Exception("wwww");
        }

        private void Close_Tapped(object sender, RoutedEventArgs e)
        {
            GetWindow(this).Close();
        }

        private double defaultWidth;
        private double defaultHeight;
        private void WindowStateChange_Tapped(object sender, RoutedEventArgs e)
        {
            var window = GetWindow(this);
            var default_btn = this.FindControl<Button>("Default_btn");
            var fullScreen_btn = this.FindControl<Button>("FullScreen_btn");
            if (window.WindowState == WindowState.FullScreen)
            {
                default_btn.IsVisible = false;
                fullScreen_btn.IsVisible = true;
                window.WindowState = WindowState.Normal;

                window.Width = this.defaultWidth;
                window.Height = this.defaultHeight;
                var workingAreaSize = window.Screens.Primary.WorkingArea.Size;
                window.Position = new PixelPoint((int)((workingAreaSize.Width - window.Width) / 2), (int)((workingAreaSize.Height - window.Height) / 2));
            }
            else
            {
                this.defaultWidth = window.Width;
                this.defaultHeight = window.Height;
                default_btn.IsVisible = true;
                fullScreen_btn.IsVisible = false;
                window.WindowState = WindowState.FullScreen;
            }
        }
        private void TitleBar_DragMove(object sender, PointerPressedEventArgs e)
        {
            GetWindow(this).BeginMoveDrag(e);
        }
    }
}
